<template>
	<view class="my-page">
		<!-- 用户信息头部 -->
		<view class="user-header">
			<view class="user-info">
				<text class="user-name">用户名：{{ userInfo.username || '未登录' }}</text>
			</view>
		</view>
		<!-- 积分卡片 -->
		<view class="points-card">
			<view class="points-header">
				<text class="title">个人总积分</text>
				<text class="points-detail" @click="navigateToPointsDetail">积分明细 ></text>
			</view>
			<view class="points-value">
				<text>{{ totalPoints }}</text>
			</view>
			<view class="points-actions">
				<button class="exchange-btn" @click="navigateToGiftExchange">兑换礼物</button>
			</view>
		</view>
		<!-- 活动记录 -->
		<view class="section">
			<view class="section-header">
				<text class="section-title">参与的活动记录</text>
				<text class="section-more" @click="navigateToAllActivities">查看全部 ></text>
			</view>
			<view class="activity-list">
				<view v-if="allActivities.length === 0" class="empty-tip">
					<text>暂无参与记录</text>
				</view>
				<view v-for="(activity, index) in displayedActivities" :key="activity.id" class="activity-item">
					<view class="activity-info">
						<text class="activity-name">{{ activity.name }}</text>
						<text class="activity-time">{{ formatTime(activity.time) }}</text>
						<text class="activity-points">{{ activity.points > 0 ? '+' : '' }}{{ activity.points }}积分</text>
					</view>
					<view class="activity-status" :class="getStatusClass(activity.status)">
						{{ getStatusText(activity.status) }}
					</view>
				</view>
				<!-- 添加查看更多提示 -->
				<view v-if="allActivities.length > 3" class="more-tip">
					<text>还有 {{ allActivities.length - 3 }} 条记录，点击"查看全部"查看</text>
				</view>
			</view>
		</view>
		<view class="function-list">
			<view class="function-item" @click="navigateToAddress">
				<text class="icon">📍</text>
				<text class="function-name">收货地址</text>
				<text class="arrow">></text>
			</view>
			<view class="function-item" @click="navigateToCertificate">
				<text class="icon">📍</text>
				<text class="function-name">活动证书</text>
				<text class="arrow">></text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		getUserInfoApi,
		getStudentPointsApi,
		getStudentActivitiesApi,
		getStudentGiftsApi
	} from '../../http/my'
	// 用户信息
	const userInfo = ref({
		id: null,
		username: '',
	})
	// 总积分
	const totalPoints = ref(0)
	// 活动记录
	const allActivities = ref([])
	const displayedActivities = computed(() => {
		// 只显示前3条活动记录
		return allActivities.value.slice(0, 3);
	})
	// 格式化时间显示
	const formatTime = (timeStr) => {
		return timeStr.replace(' ', ' · ')
	}
	// 获取活动状态文本
	const getStatusText = (status) => {
		const statusMap = {
			completed: '已完成',
			pending: '待审核',
			canceled: '已取消'
		}
		return statusMap[status] || status
	}

	// 获取活动状态类名
	const getStatusClass = (status) => {
		return `status-${status}`
	}

	// 导航到积分明细
	const navigateToPointsDetail = () => {
	  if (!userInfo.value.username) {
	    uni.showToast({
	      title: '请先登录',
	      icon: 'none'
	    })
	    return
	  }
	  
	  uni.navigateTo({
	    url: `/pages/my/point?studentName=${encodeURIComponent(userInfo.value.username)}`
	  })
	}

	// 导航到礼物兑换
	const navigateToGiftExchange = () => {
		uni.navigateTo({
			url: './gift'
		})
	}

	// 导航到所有活动
	const navigateToAllActivities = () => {
	  uni.navigateTo({
	    url: `./list?studentName=${encodeURIComponent(userInfo.value.username)}`
	  })
	}

	// 新增导航到收货地址
	const navigateToAddress = () => {
		uni.navigateTo({
			url: './address'
		});
	};
	
	// 新增导航到活动证书
	const navigateToCertificate = () => {
		uni.navigateTo({
			url: './certificate'
		});
	};

	// 页面显示时获取数据
	onShow(() => {
		fetchUserData()
	})

	// 获取用户数据
	const fetchUserData = async () => {
		const res = await getUserInfoApi();
		if (res && res.id) {
			userInfo.value = res;
			await Promise.all([
				fetchPointsData(),
				fetchActivitiesData()
			]);
		} else {
			console.error('获取用户信息失败:', res.message);
		}
	}

	// 获取积分数据
	const fetchPointsData = async () => {
		// 确保用户ID已获取
		if (!userInfo.value.id) {
			console.error('用户ID未获取，无法查询积分');
			return;
		}
		// 调用积分接口
		const res = await getStudentPointsApi(
			userInfo.value.id, // 用户ID
			100, // pageSize
			1 // pageNum
		);
		// 检查响应是否有效
		if (res) {
			totalPoints.value = res.records[0].totalPoint;
		} else {
			console.error('获取积分数据失败:', res);
			totalPoints.value = 0;
			uni.showToast({
				title: '获取积分数据失败',
				icon: 'none'
			});
		}
	}

	// 获取活动数据
	const fetchActivitiesData = async () => {
		// 确保用户ID已获取
		if (!userInfo.value.username) {
		    console.error('用户名未获取，无法查询活动记录');
		    return;
		  }
		// 调用活动接口
		const res = await getStudentActivitiesApi(
			userInfo.value.username, // 用户姓名
			1000, // pageSize
			1 // pageNum
		);
		// 检查响应是否有效
		if (res && res.records) {
			// 转换数据结构，适配前端模板
			allActivities.value = res.records.map(record => {
				// 状态映射：0 已取消, 1 已报名, 2 已打卡, 3 未打卡
				const statusMap = {
					0: 'canceled', // 已取消
					1: 'pending', // 已报名 -> 待审核
					2: 'completed', // 已打卡 -> 已完成
					3: 'pending' // 未打卡 -> 待审核
				};
				// 格式化时间：ISO时间 -> "YYYY-MM-DD HH:mm"
				const formatISOTime = (isoString) => {
					const date = new Date(isoString);
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					return `${year}-${month}-${day} ${hours}:${minutes}`;
				};

				return {
					id: record.id,
					name: record.activityName,
					time: formatISOTime(record.activityTime),
					points: record.point,
					status: statusMap[record.status] || 'pending'
				};
			});
		} else {
			console.error('获取活动数据失败:', res);
			allActivities.value = [];
			uni.showToast({
				title: '获取活动数据失败',
				icon: 'none'
			});
		}
	}
</script>

<style scoped>
	.my-page {
		padding: 20rpx 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 用户信息头部 */
	.user-header {
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.user-info {
		display: flex;
		flex-direction: column;
	}

	.user-name {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	/* 积分卡片 */
	.points-card {
		background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
		border-radius: 20rpx;
		padding: 30rpx;
		color: white;
		margin-bottom: 40rpx;
		box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.points-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.title {
		font-size: 28rpx;
	}

	.points-detail {
		font-size: 24rpx;
		text-decoration: underline;
	}

	.points-value {
		font-size: 80rpx;
		font-weight: bold;
		margin: 20rpx 0;
		text-align: center;
	}

	.points-actions {
		display: flex;
		justify-content: center;
	}

	.exchange-btn {
		background-color: rgba(255, 255, 255, 0.2);
		color: white;
		border: none;
		border-radius: 50rpx;
		padding: 10rpx 40rpx;
		font-size: 28rpx;
		backdrop-filter: blur(10rpx);
	}

	/* 分区标题 */
	.section {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
	}

	.section-more {
		font-size: 24rpx;
		color: #666;
	}

	/* 活动列表 */
	.activity-list {
		display: flex;
		flex-direction: column;
	}

	.empty-tip {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.activity-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.activity-item:last-child {
		border-bottom: none;
	}

	.activity-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.activity-name {
		font-size: 30rpx;
		margin-bottom: 10rpx;
	}

	.activity-time {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.activity-points {
		font-size: 24rpx;
		color: #4facfe;
	}

	.activity-status {
		font-size: 24rpx;
		padding: 5rpx 15rpx;
		border-radius: 20rpx;
	}

	.status-completed {
		background-color: #e6f7ff;
		color: #1890ff;
	}

	.status-pending {
		background-color: #fff7e6;
		color: #fa8c16;
	}

	.status-canceled {
		background-color: #fff1f0;
		color: #f5222d;
	}

	/* 功能列表 */
	.function-list {
		background-color: white;
		border-radius: 20rpx;
		padding: 0 30rpx;
	}

	.function-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.function-item:last-child {
		border-bottom: none;
	}

	.icon {
		margin-right: 20rpx;
		font-size: 36rpx;
	}

	.function-name {
		flex: 1;
		font-size: 30rpx;
	}

	.arrow {
		color: #999;
		font-size: 28rpx;
	}
</style>